package com.dy.dept.config;

import com.dy.dept.entity.User;
import com.dy.dept.entity.Userrole;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Auther: dy
 * @Date: 2022/3/28 - 03 - 28 - 16:06
 * @Description: com.dy.dept.config
 * @version: 1.0
 */
@Component
public class UserInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        User user = (User) session.getAttribute("user");
        if (user == null){
            return false;
        }
        List<Userrole> userrole = (List<Userrole>) session.getAttribute("userrole");

        String requestURL = request.getServletPath();//http://127.0.0.1:8080/user/login/2
        String[] split = requestURL.split("/");

        for (int i = 0; i < split.length; i++){
            for (Userrole u : userrole){
                String roleId = u.getUserRoleId().toString();// 2
                if (roleId.equals(split[i])){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
